<template>
  <article class="innerPage adminList">
    <header class="breadcrumb">
      <x-breadcrumb :path="$route.path" :title="$route.meta.breadcrumb" :startIndex="$route.meta.startIndex">
      </x-breadcrumb>
    </header>
    <section>
      <ul class="type_select">
        <div>
          <li style="margin: 0 10px">
            <div class="demonstration">关键词</div>
            <el-input v-model="filterData.keywords" placeholder="请输入" class="input_num3"></el-input>
          </li>
        </div>

        <li class="operation_btn" style="padding-right: 10px">
          <button @click="search" class="operation_btn2">查询</button>
          <button @click="reset" class="operation_btn1">重置</button>
        </li>
      </ul>
    </section>
    <div class="decorate"></div>
    <section>
      <ul class="filterBar">
        <li>
          <div class="btn_add">
            <el-button icon="el-icon-circle-plus-outline" class="btn-green icon-fontSize" @click="roleHandle()" v-alive
              >添加角色</el-button
            >
          </div>
        </li>
      </ul>
      <div class="elTable">
        <el-table
          :border="$isborder"
          stripe
          ref="elTable"
          row-key="id"
          :data="resDetail.data"
          class="tableStyle"
          :header-cell-style="$headerCellStyle"
          size="mini"
        >
          <el-table-column
            fixed
            type="index"
            :index="indexMethod"
            label="序号" label-class-name="indexColumn"
            align="center"
            width="80"
            
          >
          </el-table-column>
          <el-table-column prop="role_name" label="角色名称" :width="$widthb" align="left">
            <template slot-scope="scope">
              <div style="padding: 5px 0">{{ scope.row.role_name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="权限集合" :min-width="$widthc" align="left">
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <div slot="content" style="width: 400px">
                  {{ authFilter(scope.row.con_permission) }}
                </div>
                <p class="ellipsisText">
                  {{ authFilter(scope.row.con_permission) }}
                </p>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" :width="$widthb" align="left"> </el-table-column>
          <el-table-column prop="change_time" label="更新时间" :width="$widthb" align="left"> </el-table-column>
          <el-table-column label="操作" width="160" fixed="right" :header-align="$heaerOpt">
            <template slot-scope="scope">
              <div class="btnFrom-box">
                <div @click="tableActions(scope.row, 'revise')" class="details-box" v-alive>修改</div>
                <div @click="tableActions(scope.row, 'delete')" class="delete-box" v-alive><span></span> 删除</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </section>
    <footer class="pagination">
      <div>
        <el-pagination
          background
          prev-text="上一页"
          next-text="下一页"
          layout="prev, pager, next, jumper"
          :total="resDetail.total"
          :page-size="filterData.limit"
          @current-change="selectPage"
          :current-page.sync="resDetail.current_page"
        >
        </el-pagination>
        
      </div>
      <p>
        共<span>{{ resDetail.total || 0 }}</span
        >数据
      </p>
    </footer>

    <!-- 对话框 -->
    <x-dialog
      :visible="dialogVisible"
      dangerBtnText="确认"
      infoBtnText="取消"
      @cancel="dialogVisible = false"
      @confirm="dialogConfirm"
    >
      <div class="dialogContent">
        <x-svg-icon iconName="dialogCaution" className="iconClass"> </x-svg-icon>
        <p>{{ dialogContentText }}</p>
      </div>
    </x-dialog>
    <el-dialog
      title=""
      :visible.sync="elDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      center
      destroy-on-close
    >
      <div class="el-dialog-content">
        <div class="roleName">
          <span>角色名称</span>
          <el-input type="text" clearable placeholder="请输入角色名称" v-model="formData.role_name"> </el-input>
        </div>
        <div class="authTree">
          <span>权限选择</span>
          <el-tree
            ref="authTree"
            :data="authorityTree"
            show-checkbox
            node-key="id"
            default-expand-all
            @check="handleCheckClick"
            :props="{
              children: 'children',
              label: 'permission_name',
            }"
          >
          </el-tree>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogHandle('confirm')"> 确 定 </el-button>
        <el-button type="info" @click="dialogHandle('cancel')">取 消</el-button>
      </div>
    </el-dialog>
  </article>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      filterData: {
        keywords: "",
        page: 1,
        limit: 10,
      },
      resDetail: {
        data: [],
        total: 0,
        current_page: 0,
        selectPage: 1,
      },
      dialogVisible: false,
      dialogContentText: "",
      elDialogVisible: false,
      presentId: "",
      dialogType: "",

      formData: {
        role_name: "",
        permission_ids: "",
      },
      show_permission_ids: "",
    }
  },
  created() {},
  activated() {
    if (this.$route.params.action == "refresh" || this.$isFirstInPage.get()) {
      this.resDetail.data = []
      this.filterData.keywords = ""
      this.filterData.page = 1
      this.api()
    }

    this.setPageTabs()
    this.$refs?.elTable?.doLayout()
  },
  computed: {
    authorityTree() {
      let authorityTree = localStorage.getItem("authorityTree")
      if (authorityTree) {
        authorityTree = JSON.parse(authorityTree)
      }
      return authorityTree
    },
  },
  methods: {
    //重置
    reset() {
      this.filterData.keywords = ""
      this.filterData.page = 1
      this.api()
    },
    //查询
    search() {
      this.filterData.page = 1
      this.api()
    },
    indexMethod(i) {
      return i + 1 + (this.resDetail.current_page - 1) * 10
    },
    resetList() {
      // this.filterData = this.$options.data().filterData;
      this.api()
    },
    authFilter(arr) {
      let str = []
      arr.forEach((item, i) => {
        str.push(`${i + 1}：${item.permission_name}`)
      })
      return str.join("；")
    },
    // 获取数据
    async api() {
      try {
        let res = await this.request({
          url: "/admin/role/list",
          method: "get",
          data: {
            ...this.filterData,
          },
        })
        this.resDetail = res.content
      } catch (err) {
        this.resDetail = { data: [], total: 0, current_page: 0, selectPage: 1 }
        //  total:0,
        // current_page:0,
        // selectPage:1
        this.errorHandler(err)
      }
    },
    roleHandle(id = "") {
      this.dialogType = "add"
      this.presentId = id
      this.elDialogVisible = true
      this.$refs.authTree?.setCheckedKeys([])
      this.formData = this.$options.data().formData
    },
    handleCheckClick() {
      let ids = this.$refs.authTree.getCheckedKeys()
      let topids = this.$refs.authTree.getHalfCheckedKeys()
      let idlis = []

      if (topids.length > 0) {
        idlis = [...topids, ...ids]
      } else {
        idlis = ids
      }
      this.show_permission_ids = ids
      this.formData.permission_ids = idlis
      console.log(this.show_permission_ids, "show_permission_ids")
      console.log(this.formData.permission_ids, "permission_ids")
    },
    dialogHandle(type) {
      if (type === "cancel") {
        this.elDialogVisible = false
        this.$refs.authTree?.setCheckedKeys([])
        this.formData = this.$options.data().formData
      } else if (type === "confirm") {
        if (!this.formData.role_name) {
          this.$message({
            showClose: true,
            message: "请输入角色名称",
            type: "warning",
          })
          return
        }
        if (!this.formData.permission_ids.length) {
          this.$message({
            showClose: true,
            message: "请选择权限",
            type: "warning",
          })
          return
        }
        this.addRole()
      }
    },
    addRole() {
      let id = ""
      let url = ""
      if (this.dialogType === "revise") {
        id = this.presentId
        url = "/admin/role/change"
      } else {
        id = undefined
        url = "/admin/role/add"
      }
      this._addRole(url, id)
    },
    async _addRole(url, id) {
      let permission_ids = this.formData.permission_ids.toString()
      try {
        let res = await this.request({
          url,
          method: "post",
          data: {
            ...this.formData,
            permission_ids,
            id,
          },
        })
        this.$message({
          showClose: true,
          message: res.msg,
          type: "success",
        })
        this.elDialogVisible = false
        setTimeout(() => {
          this.api()
        }, 1000)
      } catch (err) {
        this.errorHandler(err)
      }
    },
    tableActions(row, type) {
      this.presentId = row.id
      if (type === "revise") {
        this.diinfo()
        let checkedKeys = []
        this.elDialogVisible = true
        this.dialogType = type
        this.formData.role_name = row.role_name
      } else if (type === "delete") {
        this.dialogVisible = true
        this.dialogContentText = `确定删除角色：${row.role_name}？`
      }
    },
    async dialogConfirm() {
      try {
        let res = await this.request({
          url: "/admin/role/del",
          method: "post",
          data: {
            id: this.presentId,
          },
        })
        this.$message({
          showClose: true,
          message: res.msg,
          type: "success",
        })
        this.dialogVisible = false
        setTimeout(() => {
          this.api()
        }, 1000)
      } catch (err) {
        this.errorHandler(err)
      }
    },
    async diinfo() {
      try {
        let res = await this.request({
          url: "/admin/role/detail",
          method: "get",
          data: {
            id: this.presentId,
          },
        })
        console.log(res)
        let kes = []
        res.content.con_permission.map((item, index) => {
          kes.push(Number(item.id))
        })
        console.log(kes)
        this.$nextTick(() => {
          this.$refs?.authTree?.setCheckedKeys(kes)
          // this.$refs.authTree.setCheckedKeys(kes)
        })
      } catch (err) {
        console.log(err)
        this.errorHandler(err)
      }
    },
    selectPage(i) {
      this.filterData.page = i
      this.api()
    },
  },
  watch: {},
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
